﻿using MathTutorPro.Controllers;
using MathTutorPro.Data.Entities;
using MathTutorPro.Data.DAL;
using MathTutorPro.Helper;
using MathTutorPro.Hepler;
using MathTutorPro.Models.Requests;
using MathTutorPro.Models.Responses;
using MathTutorPro.Services.Interfaces;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using static MathTutorPro.Controllers.ClassDetailController;

namespace MathTutorPro.Services.Implementations
{
    public class ClassDetailService: IClassDetailService
    {
        private readonly ClassDal _classDal;
        private readonly ClassDetailDal _classDetailDal;
        private readonly UserManager<AppUser> _userManager;
        private readonly ILogger<ClassDetailService> _logger;

        public ClassDetailService(
        ClassDal classDal,
        ClassDetailDal classDetailDal,
        UserManager<AppUser> userManager,
        ILogger<ClassDetailService> logger)
        {
            _classDal = classDal;
            _classDetailDal = classDetailDal;
            _userManager = userManager;
            _logger = logger;

            _userManager.UserValidators.Clear();
        }

        public async Task<IEnumerable<StudentResponse>> GetClassStudentsAsync(int classId, string teacherId, string keyword = null)
        {
            if (!await _classDal.ExistsAsync(classId, teacherId))
                throw new NotFoundException("班级不存在或无权操作");

            var details = await _classDetailDal.GetByClassIdAsync(classId, keyword);

            return details.Select(cd => new StudentResponse
            {
                UserId = cd.User.Id,
                StudentNo = cd.User.StudentNo,
                UserName = cd.User.UserName,
                PhoneNumber = cd.User.PhoneNumber,
                Gender = cd.User.Gender,
                Status = cd.User.Status
            });
        }


        public async Task<string> AddStudentAsync(int classId, string teacherId, StudentCreateRequest dto)
        {
            if (!await _classDal.ExistsAsync(classId, teacherId))
                throw new NotFoundException("班级不存在或无权操作");

            if (await _userManager.Users.AnyAsync(u => u.StudentNo == dto.StudentNo))
                throw new BadRequestException("学号已存在");

            var user = new AppUser
            {
                UserName = dto.UserName,
                StudentNo = dto.StudentNo,
                PhoneNumber = dto.PhoneNumber,
                Gender = dto.Gender,
                Status = 0
            };

            var createResult = await _userManager.CreateAsync(user, "abc123456");
            if (!createResult.Succeeded)
            {
                _logger.LogError("用户创建失败：{Errors}", createResult.Errors);
                throw new Hepler.ApplicationException("用户创建失败", createResult.Errors);
            }

            await _userManager.AddToRoleAsync(user, "Student");
            await _classDetailDal.AddStudentToClassAsync(classId, user.Id);

            return user.Id;
        }

        public async Task<StudentResponse> GetStudentAsync(int classId, string teacherId, string studentId)
        {
            if (!await _classDal.ExistsAsync(classId, teacherId))
                throw new NotFoundException("班级不存在或无权操作");

            if (!await _classDetailDal.IsStudentInClassAsync(classId, studentId))
                throw new NotFoundException("学生不在本班级中");

            var user = await _userManager.FindByIdAsync(studentId);
            if (user == null)
                throw new NotFoundException("学生不存在");

            return new StudentResponse
            {
                UserId = user.Id,
                StudentNo = user.StudentNo,
                UserName = user.UserName,
                PhoneNumber = user.PhoneNumber,
                Gender = user.Gender,
                Status = user.Status
            };
        }

        public async Task UpdateStudentAsync(int classId, string teacherId, string studentId, StudentUpdateRequest dto)
        {
            if (!await _classDal.ExistsAsync(classId, teacherId))
                throw new NotFoundException("班级不存在或无权操作");

            if (!await _classDetailDal.IsStudentInClassAsync(classId, studentId))
                throw new NotFoundException("学生不在本班级中");

            var user = await _userManager.FindByIdAsync(studentId);
            if (user == null)
                throw new NotFoundException("学生不存在");

            // 更新用户信息
            user.UserName = dto.UserName ?? user.UserName;
            user.PhoneNumber = dto.PhoneNumber ?? user.PhoneNumber;
            user.Gender = dto.Gender;

            var updateResult = await _userManager.UpdateAsync(user);
            if (!updateResult.Succeeded)
            {
                _logger.LogError("用户更新失败：{Errors}", updateResult.Errors);
                throw new Hepler.ApplicationException("用户更新失败", updateResult.Errors);
            }
        }

        public async Task ImportStudentsAsync(int classId, string teacherId, IFormFile file)
        {
            if (!await _classDal.ExistsAsync(classId, teacherId))
                throw new NotFoundException("班级不存在或无权操作");

            using var stream = new MemoryStream();
            await file.CopyToAsync(stream);
            stream.Position = 0;

            var students = ExcelHelper.ReadStudentList(stream);
            var successCount = 0;
            var errorMessages = new List<string>();

            foreach (var student in students)
            {
                try
                {
                    if (await _userManager.Users.AnyAsync(u => u.StudentNo == student.StudentNo))
                    {
                        errorMessages.Add($"学号 {student.StudentNo} 已存在");
                        continue;
                    }

                    var user = new AppUser
                    {
                        UserName = student.UserName,
                        StudentNo = student.StudentNo,
                        PhoneNumber = student.Phone,
                        Gender = student.Gender,
                        Status = 0
                    };

                    var result = await _userManager.CreateAsync(user, "abc123456");
                    if (result.Succeeded)
                    {
                        await _userManager.AddToRoleAsync(user, "Student");
                        await _classDetailDal.AddStudentToClassAsync(classId, user.Id);
                        successCount++;
                    }
                    else
                    {
                        errorMessages.Add($"学号 {student.StudentNo} 创建失败: {string.Join(", ", result.Errors.Select(e => e.Description))}");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "导入学生时发生错误");
                    errorMessages.Add($"学号 {student.StudentNo} 导入失败: {ex.Message}");
                }
            }

            if (errorMessages.Any())
            {
                throw new Hepler.ApplicationException(
                    $"成功导入 {successCount} 个学生，失败 {errorMessages.Count} 个。错误详情: {string.Join("; ", errorMessages)}");
            }
        }

    }
}
